<template>
  <div :class="{'container-padding': !showMobilePage}" class="container">
    <Step v-if="!showMobilePage" :process="process"/>
    <div class="main-box">
      <AccountList v-if="process === 0" ref="accountListRef" :show-mobile-page="showMobilePage" @changeSelect="changeSelect"/>
      <div v-if="process === 1">
        <explanation :explanation="explanationObj" is-expand class="explanation" style="margin: 0;"/>
        <Title title="创建信息" style="margin:16px 0 7px;" />
        <el-form
          ref="baseform"
          :model="paramsObj"
          :label-position="showMobilePage?'left':'right'"
          :class="{'mobile-el-form': showMobilePage}"
          class="lineHeight32 create-form"
          label-width="165px">
          <el-row :class="{'dividing': !showMobilePage}" class="response-el-row" type="flex">
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="申请人：">
                <CheckUserInfo :user-id="userInfo.id" :label="userInfo.userName" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="申请人部门：">
                <span>{{ userInfo.departmentName ? userInfo.departmentName[0] : '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="申请人职位：">
                <span>{{ userInfo.post }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <ShowInfo :show-mobile-page="showMobilePage" :account-info="accountInfo" :platform-fields="getFields()" :platform-name="platformName"/>
      </div>
      <audit-process
        ref="auditProcessRef"
        :loading="btnLoading"
        v-model="auditInfo"
        :old-audit-info="oldAuditInfo"
        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="toSubmit(SUBMITTYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <fixed-pagination>
        <div v-if="process === 0" class="center">
          <el-button size="small" type="primary" @click="toNext">下一步</el-button>
          <el-button class="cancel-btn-style" size="small" type="info" @click="toUpOnlineList">返回列表</el-button>
        </div>
        <div v-if="process === 1 && !showMobilePage" class="center">
          <el-button type="primary" size="small" plain class="empty-btn-style" @click="toBack">上一步</el-button>
          <el-button :loading="freshLoading" type="primary" size="small" plain class="empty-btn-style" @click="toNext(true)">刷新资源</el-button>
          <el-button v-if="hasRouteAuth('crm:upOline:edit')" type="primary" size="small" plain class="empty-btn-style" @click="toAccount">编辑资源</el-button>
          <el-button size="small" type="primary" @click="openDrawer">发起审批</el-button>
          <el-button v-if="(!remodifyId && !reapplyId) || createNew" type="primary" size="small" plain class="empty-btn-style" @click="toSubmit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
          <el-button class="cancel-btn-style" size="small" type="info" @click="toUpOnlineList">返回列表</el-button>
        </div>
        <div v-if="process === 1 && showMobilePage" :class="{'is-mobile': showMobilePage}" class="center">
          <el-button size="small" type="primary" style="margin-right: 10px;" @click="openDrawer">发起审批</el-button>
          <el-button type="primary" size="small" plain class="empty-btn-style" style="margin-right: 10px;" @click="toBack">上一步</el-button>
          <el-dropdown placement="top">
            <div class="mobile-icon">
              <el-image :src="mobileIcon" class="img"/>
              <span class="text">更多</span>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="hasRouteAuth('crm:upOline:edit')">
                <div @click="toAccount">编辑资源</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="toNext">刷新资源</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="(!remodifyId && !reapplyId) || createNew">
                <div @click="toSubmit(SUBMITTYPE.DRAFT)">保存草稿</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="toUpOnlineList">返回列表</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import Title from '@/components/Title';
import ShowInfo from './components/showInfo.vue';
import AccountList from './components/accountList.vue';
import Step from './components/step';
import { createAuditStructure } from '@/utils/aduitor';
import ElMessage, { showModal } from '@/utils/message';
import { SUBMITTYPE } from '@/utils/const/cost';
import { hasRouteAuth } from '@/utils/permission';
import { processManagementDetail } from '@/api/legal';
import { getUpOnlineAccount, submitUpOnlineForm, createUpOnline, editUpOnline, upOnlineDetail } from '@/api/upOnline';
import { isContained } from '@/utils/tools';
import processCreate from '@/mixins/processCreate';
import mobileIcon from '@/assets/mobileIcon/moreOperate.png';
import { redbookFields, douyinFields, weiboFields, bilibiliFields, kuaishouFields, weixinFields, weixinVideoFields } from './components/data';
import upMixin from './mixin';

export default {
  components: { AccountList, AuditProcess, explanation, Step, Title, ShowInfo },
  mixins: [processCreate, upMixin],
  data() {
    return {
      mobileIcon,
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      process: 0, // 控制进度条, 选择账号(0) 填写信息(1) 上刊审批(2) 流程结束(4)
      paramsObj: {},
      SUBMITTYPE,
      accountInfo: {},
      btnLoading: false,
      processDetail: null,
      remodifyId: null, // 修改，审批流程不能修改
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      // 流程信息
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      resourceId: null,
      platformName: '',
      freshLoading: false,
      createNew: 0,
      upOnlineId: 0,
      isRefresh: false,
      isEdit: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
    const { resourceId, remodifyId, reapplyId, platformName, createNew, id } = this.$route.query;
    this.resourceId = Number(resourceId);
    this.platformName = platformName;
    this.upOnlineId = id || remodifyId;
    this.remodifyId = remodifyId; // 修改
    this.reapplyId = reapplyId; // 重新申请
    this.createNew = createNew || 0; // 重新申请
    if (resourceId && platformName) {
      this.toNext();
    }
    if (this.upOnlineId || this.resourceId) {
      this.isEdit = true;
      if (this.upOnlineId) {
        this.getDetailData();
      }
    } else {
      this.isEdit = false;
    }
    this.getExplanation();
  },
  methods: {
    hasRouteAuth,
    getFields() {
      return {
        '小红书': redbookFields,
        'B站': bilibiliFields,
        '抖音': douyinFields,
        '微博': weiboFields,
        '快手': kuaishouFields,
        '微信': weixinFields,
        '微信视频号': weixinVideoFields
      }[this.platformName];
    },
    getExplanation() { // 获取审批说明
      // 达人上刊type为26
      processManagementDetail({ id: 3527, type: 26 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    changeSelect(val) {
      this.resourceId = val.resourceId;
      this.platformName = val.platformName;
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    changeValue(val) {
      this.resourceId = val;
    },
    toNext(isFresh = false) {
      if (this.resourceId) {
        if (isFresh) {
          this.freshLoading = true;
        }
        getUpOnlineAccount({ resourceId: this.resourceId }).then(res => {
          if (res.code === 200) {
            this.process = 1;
            this.accountInfo = res.data;
          }
        }).catch().finally(_ => {
          if (isFresh) {
            this.freshLoading = false;
          }
        });
      } else {
        ElMessage.warning('请选择账号！');
      }
    },
    toUpOnlineList() {
      this.$router.push({
        name: 'upOnline'
      });
    },
    toBack() {
      if (this.remodifyId) {
        this.processId = this.remodifyId;
      }
      if (this.reapplyId) {
        this.processId = this.reapplyId;
      }
      this.process = 0;
      setTimeout(() => {
        this.$refs.accountListRef && (this.$refs.accountListRef.singleSelect = this.resourceId);
      }, 200);
    },
    getDetailData() {
      upOnlineDetail(this.upOnlineId).then(res => {
        if (res.code === 200) {
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
      });
    },
    getProcessDetail(isRefresh) {
      const params = { resourceId: this.resourceId, applicantId: this.userInfo.id };
      params.type = 26; // 流程类型，达人上刊
      this.btnLoading = true;
      submitUpOnlineForm(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcessRef'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcessRef'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    openDrawer() {
      // 先判断必填字段是否必填
      this.handleValidate();
      this.getProcessDetail();
    },
    toSubmit(submitType = SUBMITTYPE.SUBMIT, senders = []) {
      this.modifySenders = senders;// 存到mixins
      // 处理参数
      const params = { resourceId: this.resourceId, applicantId: this.userInfo.id };
      params.submitType = submitType;
      if (submitType !== SUBMITTYPE.DRAFT && this.reapplyId && !this.createNew) { // 重新提交
        params.submitType = SUBMITTYPE.RESUBMIT;
      }
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      if (this.createNew) {
        delete params.id;
      }
      if (this.remodifyId) {
        params.id = this.remodifyId;
      }
      params.auditInfo = this.auditInfo;
      const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      if (this.isEdit && !this.createNew) {
        showModal(msg).then(() => {
          this.handleModifyData(params);
          this.edit(params);
        });
      } else {
        showModal(msg).then(() => this.create(params));
      }
    },
    create(params) {
      this.btnLoading = true;
      createUpOnline(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'upOnlineDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.$router.push({ name: 'upOnline' });
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        this.btnLoading = false;
      });
    },
    edit(params) {
      this.btnLoading = true;
      editUpOnline(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'upOnlineDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.$router.push({ name: 'upOnline' });
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        this.btnLoading = false;
      });
    },
    toAccount() {
      if (this.hasRouteAuth('medium:resource:admin')) {
        const routeUrl = this.$router.resolve({
          name: 'detailResource',
          params: { resourceId: this.accountInfo.id }
        });
        window.open(routeUrl.href, '_blank');
      } else {
        this.$message.warning('您暂无账号资源可读权限，请联系管理员添加');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: calc(100vh - 80px);
  margin: 16px;
  background-color: #fff;
  .main-box {
    padding: 0 24px;
  }
  .width240 {
    width: 240px;
  }
}
.container-padding {
  padding-bottom: 56px;
}
.create-form {
  &::v-deep {
    .dividing{
      .el-col {
        padding-right: 0 !important;
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:nth-child(3n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
      .el-col:nth-child(even) {
        padding-left: 0 !important;
      }
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
.mobile-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  .text {
    font-size: 10px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #aeb6c7;
    line-height: 14px;
    margin-top: 2px;
  }
  .img{
    width: 24px;
    height: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
